package com.xs.ai.controller;

import com.xs.ai.dto.MeetingAnalysisResult;
import com.xs.ai.dto.MeetingResponseRequest;
import com.xs.ai.dto.ResourceNotFoundException;
import com.xs.ai.entity.CalendarEvent;
import com.xs.ai.entity.User;
import com.xs.ai.services.CalendarOptimizationService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1")
@RequiredArgsConstructor
public class CalendarController {

    private final CalendarOptimizationService calendarService;

    /**
     * 获取今日会议
     */
    @GetMapping("/calendar/today")
    public ResponseEntity<List<CalendarEvent>> getTodayMeetings(@RequestParam Long userId) {
        LocalDate today = LocalDate.now();
        List<CalendarEvent> meetings = calendarRepository.findByUserAndDate(userId, today);
        return ResponseEntity.ok(meetings);
    }

    /**
     * 分析会议请求
     */
    @PostMapping("/calendar/meetings/{meetingId}/analyze")
    public ResponseEntity<MeetingAnalysisResult> analyzeMeeting(
            @PathVariable Long meetingId,
            @RequestParam Long userId) {

        CalendarEvent meeting = calendarRepository.findById(meetingId)
                .orElseThrow(() -> new ResourceNotFoundException("会议不存在"));

        User user = userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在"));

        MeetingAnalysisResult result = calendarService.analyzeMeetingRequest(meeting, user);

        return ResponseEntity.ok(result);
    }

    /**
     * 响应会议邀请
     */
    @PostMapping("/calendar/meetings/{meetingId}/respond")
    public ResponseEntity<Map<String, String>> respondToMeeting(
            @PathVariable Long meetingId,
            @RequestBody MeetingResponseRequest request) {

        calendarService.respondToMeeting(meetingId, request.getResponse(), request.getMessage());

        return ResponseEntity.ok(Map.of("status", "success"));
    }

    /**
     * 优化本周日程
     */
    @PostMapping("/calendar/optimize-week")
    public ResponseEntity<WeekOptimizationResult> optimizeWeek(@RequestParam Long userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在"));

        LocalDate weekStart = LocalDate.now().with(DayOfWeek.MONDAY);
        WeekOptimizationResult result = calendarService.optimizeWeekSchedule(user, weekStart);

        return ResponseEntity.ok(result);
    }
}
